package cn.kgc.springboot.vue.shiro;

import jakarta.servlet.Filter;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @author 课工场
 * @date 2024/12/19
 * @description shiro安全框架全局配置
 */
@Configuration
public class ShiroWebConfig {

    //  过滤器链
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        // 设置安全规则
        LinkedHashMap<String, String> map = new LinkedHashMap<>();

        // 添加自定义filter
        HashMap<String, Filter> filterHashMap = new HashMap<>();
        filterHashMap.put("jwt",new JwtTokenFilter());

        // 放行
        map.put("/user/auth","anon");
        map.put("/captcha","anon");
        map.put("/user/login","anon");
        // map.put("/user/menu","anon");
        // map.put("/**","authc");

        // 放行swagger相关请求
        map.put("/doc.html","anon");
        map.put("/swagger-resources", "anon");
        map.put("/favicon.ico", "anon");
        map.put("/v3/api-docs/**", "anon");
        map.put("/webjars/**", "anon");


        map.put("/**","jwt");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        shiroFilterFactoryBean.setFilters(filterHashMap);
        // 设置的登录路径
        shiroFilterFactoryBean.setLoginUrl("/user/unAuth");
        return shiroFilterFactoryBean;
    }

    // 安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(CustomerRealm customerRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(customerRealm);
        return defaultWebSecurityManager;
    }

    // 自定义realm
    @Bean
    public CustomerRealm customerRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        return customerRealm;
    }


}
